package com.example.chapter5.service.iml;


import com.example.chapter5.entity.UserPOJO;
import com.example.chapter5.mapper.UserMapper;
import com.example.chapter5.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceIml implements UserService {
    @Autowired
    UserMapper userMapper;


    @Override
    public User login(String username, String password) {
        //通过用户名查询数据库的用户数据
        UserPOJO userpo = userMapper.findByUsername(username);
        //如果查询不到，就抛出用户名不存在的异常
        if (userpo == null) {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
        //判断密码是否正确
        if (!password.equals(userpo.getPassword())) {
            //密码错误
            throw new RuntimeException("Password Error");
        }
        //返回User对象
        User user = (User) User.withUsername(username)
                .username(username)
                .password(password)
                .authorities(userpo.getRole())
                .build();
        return user;
    }
}
